package server

import (
	"coolcar/v1/shared/auth"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"net"
)

type Config struct {
	Name              string
	Addr              string
	AuthPublicKeyFile string
	RegisterFunc      func(*grpc.Server)
	Suger             *zap.SugaredLogger
}

// RunGRPCServer runs a grpc server.
func RunGRPCServer(c *Config) error {
	nameField := zap.String("name", c.Name)
	lis, err := net.Listen("tcp", c.Addr)
	if err != nil {
		c.Suger.Fatalf("%v: failed to listen: %v", nameField, err)
	}

	var opts []grpc.ServerOption
	if c.AuthPublicKeyFile != "" {
		interceptor, err := auth.Interceptor(c.AuthPublicKeyFile)
		if err != nil {
			c.Suger.Fatalf("%v: failed to create interceptor: %v", nameField, err)
		}
		opts = append(opts, grpc.UnaryInterceptor(interceptor))
	}

	s := grpc.NewServer(opts...)
	c.RegisterFunc(s)
	c.Suger.Infof("%v: server listening at %v", c.Name, c.Addr)
	return s.Serve(lis)
}
